package com.epam.kulibaba.components.compareTable;

import java.util.HashMap;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.Reporter;

import com.epam.kulibaba.components.catalog.ProductsCatalog;
import com.epam.kulibaba.helpers.testSupport.ProductsListHelper;

public class CompareTable {

	public static final String COMPARETABLE = ".//div[@id = 'page-content-wrap']//tbody";

	@FindBy(xpath = CompareTable.COMPARETABLE)
	WebElement compareTable;

	public WebElement getCompareTable() {
		return compareTable;
	}
	
	public static CompareTable getProductsCatalog(WebDriver driver) {
		CompareTable compareTable = PageFactory.initElements(driver,
				CompareTable.class);
		return compareTable;
	}
	
	public static HashMap<String, String> productDescriptionsInCompare(
			CompareTable compareTable, int productNumber) {
		Reporter.log("Get product description on compare page");
		HashMap<String, String> productCompareDescription = new HashMap<String, String>();
				List<WebElement> rowCompareDescriptions = compareTable
				.getCompareTable()
				.findElements(
						By.xpath("//tr[@class = ''] | //tr[@class = 'different']"));
		for (WebElement row : rowCompareDescriptions) {
			String name = row.findElement(By.xpath(".//td[1]")).getText()
					.toLowerCase();
			String value = row.findElement(By.xpath(".//td[last()]")).getText()
					.toLowerCase();
			productCompareDescription.put(name, value);
		}
		
		  /*System.out.println("-------------");
		  
		  for (Map.Entry me : productCompareDescription.entrySet()) {
		  System.out.println(me.getKey() + " " + me.getValue()); }*/
		 
		return productCompareDescription;
	}

	public static void checkColorDifferentDescriptions(
			CompareTable compareTable, Double numbersOfProducts,
			ProductsCatalog productCatalog) {
		Reporter.log("check different options in products on compare page");
		ProductsCatalog.goToProductsCompare(productCatalog,
				(int) numbersOfProducts.doubleValue());
		List<WebElement> rowCompareDescriptions = compareTable
				.getCompareTable()
				.findElements(
						By.xpath("//tr[@class = ''] | //tr[@class = 'different']"));
		for (WebElement row : rowCompareDescriptions) {
			List<WebElement> cells = row.findElements(By.xpath(".//td"));
			for (int cellIndex = 1; cellIndex < cells.size() - 1; cellIndex++) {
				if (!cells.get(cellIndex).getText()
						.equalsIgnoreCase(cells.get(cellIndex + 1).getText())) {
					Assert.assertEquals(row.getAttribute("class"), "different");
					/*
					 * System.out.println(cells.get(cellIndex).getText() +
					 * " >>>> " + cells.get(cellIndex + 1).getText());
					 */
					break;
				}
			}
		}
	}

}
